using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.IO;
using System.Linq;
using System.Reflection;
using util.AttributeExtension;
using util.EnumExtion;
using System.ComponentModel;

namespace util.ServiceExtion
{
    public static class SwaggerService
    {
        public static IServiceCollection AddMySwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                var apiGroupNames = Enum.GetValues(typeof(ApiGroupNameEnum));
                foreach (var item in apiGroupNames)
                {
                    var index = Convert.ToInt32(item);
                    var value = item.ToString();
                    var des = item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true)[0] as DescriptionAttribute;
                    c.SwaggerDoc(value, new OpenApiInfo { Title = des.Description, Version = value });
                }

                c.DocInclusionPredicate((docName, apiDes) =>
                  {
                      if (!apiDes.TryGetMethodInfo(out MethodInfo method))
                      {
                          return false;
                      }
                      var versionEnum = method.DeclaringType.GetCustomAttributes(true).OfType<ApiGroupNameAttribute>().Select(m => m.apiGroupName).FirstOrDefault();
                      var version = versionEnum.ToString();
                      if (docName == "v1" && !version.Any())
                      {
                          return true;
                      }

                      //这里获取action的特性
                      var actionVersion = method.GetCustomAttributes(true).OfType<ApiGroupNameAttribute>().Select(m => m.apiGroupName).FirstOrDefault();
                      if (Enum.IsDefined(typeof(ApiGroupNameEnum), actionVersion))
                      {
                          return true;
                      }
                      return version == docName;
                  });

                var basePath = Environment.CurrentDirectory;
                var xmlPath = Path.Combine(basePath, "openapi.xml");
                //var xmlmodelPath = Path.Combine(basePath, "entity.xml");//添加model注释
                //c.IncludeXmlComments(xmlmodelPath);
                c.IncludeXmlComments(xmlPath, true);//controller注释;必须放最后,否则后面的会覆盖前面的

            });
            return services;
        }
    }
}